package main

import (
	"errors"
	pb "gRPC/serviceH/proto"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/metadata"
	"log"
	"net"
)

type server struct {
	pb.UnimplementedSayHelloServer
}

// 业务
func (s *server) SayHello(ctx context.Context, req *pb.HelloRequest) (*pb.HelloResponse, error) {
	//获取元数据信息
	md, ok := metadata.FromIncomingContext(ctx)
	if !ok {
		return nil, errors.New("没传输token")
	}
	var appId string
	var appKey string
	if val, ok := md["appid"]; ok {
		appId = val[0]
	}
	if val, ok := md["appkey"]; ok {
		appKey = val[0]
	}
	if appId != "CCC" || appKey != "JJJ" {
		return nil, errors.New("token不正确")
	}

	return &pb.HelloResponse{ResponseMsg: "hello" + req.RequestName}, nil

}

func main() {
	//开启端口
	lis, _ := net.Listen("tcp", ":8080")
	//创建grpc服务
	grpcServer := grpc.NewServer(grpc.Creds(insecure.NewCredentials()))
	//在grpc服务端中去注册我们自己的编写的服务
	pb.RegisterSayHelloServer(grpcServer, &server{})
	//启动服务
	err := grpcServer.Serve(lis)
	if err != nil {
		log.Fatalf("failed to 启动  serve: %v", err)
	}
}
